<?php

namespace App\DB;

use DB;
use App\Exceptions\ReqException;

class UserDB {
	/**
	 * 根据uid来获取客户信息
	 *
	 * @param unknown $uid        	
	 * @return unknown
	 */
	public static function getUserByUid($uid) {
		if (! is_empty_or_null_string ( $uid )) {
			$sql = 'select uid, level, name, company, address, phone, logo_url, description, active, created_at from sys_users where uid = ?';
			$params = [ 
					$uid 
			];
			$users = DB::select ( $sql, $params );
			return $users [0];
		} else {
			$sql = 'select uid, level, name, company, address, phone, logo_url, description, active, created_at from sys_users';
			$users = DB::select ( $sql );
			return $users;
		}
	}
	
	/**
	 * 根据id获取用户信息
	 *
	 * @param unknown $id        	
	 * @return unknown
	 */
	public static function getUserById($id) {
		$sql = 'select uid, `level`, `name`, company, address, phone, logo_url, description, active, created_at from sys_users where id = ?';
		$params = [ 
				$id 
		];
		$users = DB::select ( $sql, $params );
		return $users [0];
	}
	
	/**
	 * 添加用户
	 *
	 * @param unknown $uid        	
	 * @param unknown $password        	
	 * @param unknown $name        	
	 * @param unknown $company        	
	 * @param unknown $address        	
	 * @param unknown $phone        	
	 * @param unknown $logo_url        	
	 * @param unknown $description        	
	 */
	public static function addUser($user) {
		$sql = 'insert into sys_users(uid, `password`, `level`, `name`, company, address, phone, logo_url, description, active, created_at, updated_at) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
		$params = [ 
				$user->uid,
				strtolower ( $user->password ),
				'2',
				$user->name,
				$user->company,
				$user->address,
				$user->phone,
				$user->logo_url,
				$user->description,
				'1',
				date ( "Y-m-d H:i:s" ),
				date ( "Y-m-d H:i:s" ) 
		];
		DB::insert ( $sql, $params );
		
		$sql2 = 'insert into sys_user_role(uid, role_id) values(?, ?)';
		$params2 = [ 
				$user->uid,
				$user->role_id 
		];
		DB::insert ( $sql2, $params2 );
		
		return true;
	}
	/**
	 * 删除用户
	 *
	 * @param unknown $uid        	
	 */
	public static function deleteUser($user) {
		$sql = 'delete from sys_users where uid = ?';
		$params = [ 
				$user->uid 
		];
		return DB::delete ( $sql, $params );
	}
	
	/**
	 * 更新用户信息
	 *
	 * @param unknown $uid        	
	 * @param unknown $active        	
	 */
	public static function updateUser($user) {
		$sql = 'update sys_users set active = ?, updated_at =  ? where uid = ?';
		$params = [ 
				$user->active,
				date ( "Y-m-d H:i:s" ),
				$user->uid 
		];
		return DB::update ( $sql, $params );
	}
}
